import mx.events.EventDispatcher;
import mx.utils.Delegate;

import org.molamil.acto.commands.CommandsFactoryFinisher;
import org.molamil.acto.commands.CommandsParser;
import org.molamil.acto.commands.factory.BasicCommandFactory;
import org.molamil.acto.core.EventConstants;
import org.molamil.acto.core.Logger;

/**
 * @author Jorge Hernandez
 */
class org.molamil.acto.commands.factory.XmlCommandFactory extends BasicCommandFactory {
	
	
	// Properties
	
	private static var log:Logger = Logger.getLogger("XmlCommandFactory");
	
	private var xmlConf:XML;
	private var xmlConfLoadDelegate:Function;
	
	public var dispatchEvent:Function;
 	public var addEventListener:Function;
	public var removeEventListener:Function;
	
	
	// Constructor
	
	/**
	 * Creates a new XmlCommandFactory that will use an XML configuration.
	 */
	public function XmlCommandFactory(source:Object) {
		log.debug("Constructor");
		EventDispatcher.initialize(this);
	}
	
	
	// Functions
	
	/**
	 * Loads the XML configuration.
	 * 
	 * @param   source Object parameter with two usages:
	 * <ul>
	 * 	<li>As an <code>XML</code> object: Parses the XML data directly.</li>
	 * 	<li>As a <code>String</code> object: Loads the XML file located on source and parses the content.</li>
	 * </ul>
	 */
	public function loadConf(source:Object):Void {
		log.debug("loadConf");
		if (source instanceof XML) {
			log.debug("source is an XML object");
			xmlConf = XML(source);
			doParse();
			var eventObject:Object = {target: this, type: EventConstants.COMMANDS_CONF_LOAD};
			dispatchEvent(eventObject);
		} else {
			log.debug("source is a path");
			xmlConfLoadDelegate = Delegate.create(this, onXmlConfLoadListener);
			xmlConf = new XML();
			xmlConf.ignoreWhite = true;
			xmlConf.onLoad = xmlConfLoadDelegate;
			xmlConf.load(String(source));
		}
	}
		
	private function doParse():Void {
		_list = CommandsParser.parse(xmlConf);
		CommandsFactoryFinisher.run(this);
	}
	
	
	// Listeners
	
	private function onXmlConfLoadListener(success:Boolean):Void {
		log.debug("onXmlConfLoadListener(), success = " + success);
		if (success) {
			doParse();
			var eventObject:Object = {target: this, type: EventConstants.COMMANDS_CONF_LOAD};
			dispatchEvent(eventObject);
		} else {
			var eventObject:Object = {target: this, type: EventConstants.CONF_LOAD_ERROR};
			dispatchEvent(eventObject);
		}
	}
	
	
}
